    package com.tcode.servlet;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.tcode.bean.UserBean;
import com.tcode.service.UserService;
import com.tcode.utils.BeanFactory;
import com.tcode.utils.DownLoadUtils;

/**
 * Servlet implementation class ExpImpServlet
 */
@WebServlet("/ExpImpServlet")
@MultipartConfig
public class ExpImpServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	UserService us = (UserService) BeanFactory.getBean("UserService");   
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ExpImpServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    public String exp(HttpServletRequest request, HttpServletResponse response){
    	response.setContentType("application/vnd.ms-excel;charset=utf-8");  
        response.addHeader("Content-Disposition", "attachment;filename=Test.csv");  
        try {
			List<UserBean> list = us.getUserForExcel();
			DataOutputStream stream=new  DataOutputStream(response.getOutputStream());  
            String content="uid,姓名,密码,创建时间,部门ID\n";  
            stream.write(content.getBytes("GBK"));  
            
            for (UserBean userBean : list) {
            	content=userBean.getId()+","+userBean.getName()+","+userBean.getPhone()+
            			","+userBean.getCreatedate()+",暂无 \n";
            	stream.write(content.getBytes("GBK"));  
			}
            stream.flush();  
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return null;
    } 
    
    public void download(HttpServletRequest request, HttpServletResponse response) throws IOException{
    	 //1.获取请求参数，文件名称
        String filename = request.getParameter("filename");
        //2.使用字节输入流加载文件进内存
        //2.1找到文件服务器路径
        ServletContext servletContext = this.getServletContext();
        String realPath = servletContext.getRealPath("/img/" + filename);
        //2.2用字节流关联
        FileInputStream fis = new FileInputStream(realPath);

        //3.设置response的响应头
        //3.1设置响应头类型：content-type
        String mimeType = servletContext.getMimeType(filename);//获取文件的mime类型
        
        System.out.println("content-type="+mimeType);
        
        response.setHeader("content-type",mimeType);
        //3.2设置响应头打开方式:content-disposition

        //解决中文文件名问题
        //1.获取user-agent请求头、
        String agent = request.getHeader("user-agent");
        //2.使用工具类方法编码文件名即可
        filename = DownLoadUtils.getFileName(agent, filename);

        response.setHeader("content-disposition","attachment;filename="+filename);
        //4.将输入流的数据写出到输出流中
        ServletOutputStream sos = response.getOutputStream();
        byte[] buff = new byte[1024 * 8];
        int len = 0;
        while((len = fis.read(buff)) != -1){
            sos.write(buff,0,len);
        }

        fis.close();

    }
    
    public void imp(HttpServletRequest request, HttpServletResponse response) throws IllegalStateException, IOException, ServletException{
    	//存储路径
    	String savePath = request.getServletContext().getRealPath("/WEB-INF/upload");
    	
    	//获取上传的文件集合
    	Collection<Part> parts = request.getParts();
    	
    	String tip="没有数据";
    	//上传单个文件
    	if (parts.size()==1) {
    		//Servlet3.0将multipart/form-data的POST请求封装成Part，通过Part对上传的文件进行操作。
    		//Part part = parts[0];//从上传的文件集合中获取Part对象
    		Part part = request.getPart("file");//通过表单file控件(<input type="file" name="file">)的名字直接获取Part对象
    		//Servlet3没有提供直接获取文件名的方法,需要从请求头中解析出来
    		//获取请求头，请求头的格式：form-data; name="file"; filename="snmp4j--api.zip"
    		String header = part.getHeader("content-disposition");
    		System.out.println(header);
    		
    		String filelongName =header.split(";")[header.split(";").length-1];
    		
//    		System.out.println(filelongName.split("\\\\")[filelongName.split("\\\\").length-1].substring(0, filelongName.split("\\\\")[filelongName.split("\\\\").length-1].length()-1));
    		//获取文件名
    		String fileName = filelongName.
    				split("\\\\")[filelongName.split("\\\\").length-1].
    				substring(0, filelongName.split("\\\\")
    						[filelongName.split("\\\\").length-1].length()-1);//;
    		//把文件写到指定路径
    		part.write(savePath+File.separator+fileName);
    		tip="上传成功";
    	}
    	PrintWriter out = response.getWriter();
    	out.println(tip);
    	out.flush();
    	out.close();

    	 
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String method =request.getParameter("_method");
		if("exp".equals(method)){
			exp(request, response);
		}else if("download".equals(method)){
			download(request, response);
		}else if("".equals(method)){
			
		}else{
			imp(request, response);
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
